package com.shopping.servlets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/***
 * 核心Servlet，该Servlet负责对所有请求进行统一调配
 * 根据请求不同将不同的请求转给不同的具体的Servlet进行处理
 */
public class BaseServlet extends HttpServlet {
    protected PrintWriter out;
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应内容的编码集类型
        response.setContentType("json/application;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        try {
            out = response.getWriter();
            //获得客户端传入的operate参数
            String methodName = request.getParameter("operate");
            //根据方法名和方法的参数获得方法对象(参数为HttpServletRequest,HttpServletResponse)
            Method method = getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            //调用方法
            method.invoke(this,request,response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

